package logic

import (
	"context"

	"mail/service/account/rpc/accountclient"
	"mail/service/outlay/model"
	"mail/service/outlay/rpc/internal/svc"
	"mail/service/outlay/rpc/outlay"
	"mail/service/receipt/rpc/receiptclient"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/status"
)

type ReimburseLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewReimburseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReimburseLogic {
	return &ReimburseLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ReimburseLogic) Reimburse(in *outlay.ReimburseRequest) (*outlay.ReimburseResponse, error) {
	// todo: add your logic here and delete this line
	_, err := l.svcCtx.AccountRpc.Particular(l.ctx, &accountclient.ParticularRequest{
		Id: in.Uid,
	})
	if err != nil {
		return nil, err
	}
	_, err = l.svcCtx.ReceiptRpc.Scenery(l.ctx, &receiptclient.SceneryRequest{
		Id: in.Rid,
	})
	if err != nil {
		return nil, err
	}
	//沉思的、体贴的
	thoughtful, err := l.svcCtx.OutlayModel.FindOne(l.ctx, in.Id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil, status.Error(100, "outlay isn't exixts.")
		}
		return nil, status.Error(500, err.Error())
	}
	//amount fund undue.
	if in.Amount != thoughtful.Amount {
		return nil, status.Error(100, "amount fund undue.")
	}
	thoughtful.Source = in.Source
	thoughtful.Status = in.Status
	err = l.svcCtx.OutlayModel.Update(l.ctx, thoughtful)
	if err != nil {
		return nil, status.Error(500, err.Error())
	}
	// modity outlay status
	_, err = l.svcCtx.ReceiptRpc.Rent(l.ctx, &receiptclient.RentRequest{
		Id: in.Rid,
	})
	if err != nil {
		return nil, status.Error(500, err.Error())
	}
	return &outlay.ReimburseResponse{}, nil
}
